package com.csu.csumall.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.csumall.VO.CartVO;
import com.csu.csumall.common.CartStatus;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.entity.Cart;
import com.csu.csumall.entity.Product;
import com.csu.csumall.mapper.CartMapper;
import com.csu.csumall.mapper.ProductMapper;
import com.csu.csumall.service.ICartVOService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("cartVOService")
public class CartVOServiceImp implements ICartVOService {

    private final CartMapper cartMapper;
    private final ProductMapper productMapper;

    public CartVOServiceImp(CartMapper cartMapper, ProductMapper productMapper) {
        this.cartMapper = cartMapper;
        this.productMapper = productMapper;
    }

    @Override
    public List<CartVO> listChecked(Integer userId) {
        List<Cart> cartList = cartMapper.selectList(
                new QueryWrapper<Cart>().eq("user_id", userId)
                        .eq("status", ItemStatus.ENABLE.getValue())
                        .eq("checked", CartStatus.CHECKED.getValue())
        );
        List<CartVO> cartVOList = new ArrayList<>();
        cartList.forEach(cart -> {
            cartVOList.add(
                    new CartVO(cart,
                            productMapper.selectOne(new QueryWrapper<Product>().eq("id", cart.getProductId()))));
        });
        return cartVOList;
    }

    @Override
    public List<CartVO> listByUserId(Integer id) {
        List<Cart> cartList = cartMapper.selectList(
                new QueryWrapper<Cart>().eq("user_id", id).eq("status", ItemStatus.ENABLE.getValue())
        );
        List<CartVO> cartVOList = new ArrayList<>();
        cartList.forEach(cart -> {
            cartVOList.add(
                    new CartVO(cart,
                            productMapper.selectOne(new QueryWrapper<Product>().eq("id", cart.getProductId()))));
        });
        return cartVOList;
    }

    @Override
    public CartVO getOne(Integer userId, Integer productId) {
        Cart cart = cartMapper.selectOne(
                new QueryWrapper<Cart>().eq("user_id", userId).eq("product_id", productId)
        );
        Product product = productMapper.selectById(productId);
        return new CartVO(cart, product);
    }

}
